import FingerprintJS from '@fingerprintjs/fingerprintjs'
import { parse } from 'querystring'

export const StoreKey = {
    ELECTRON_MACHINE_ID: 'ELECTRON_MACHINE_ID',
    TOKEN: 'FIRE_TOKEN',
    USER_INFO: 'USER_INFO',
}

export const getUser = async () => {
    return await getStore(StoreKey.USER_INFO)
}
export const getMachineId = async () => {
    let machineId = await getStore(StoreKey.ELECTRON_MACHINE_ID)
    if (!machineId) {
        const fp = await FingerprintJS.load()
        const result = await fp.get()
        machineId = result.visitorId
        await setStore(StoreKey.ELECTRON_MACHINE_ID, machineId)
    }
    return machineId
}
export const setStore = async (key: string, value: any) => {
    try {
        value = JSON.stringify(value)
    } catch (e) {}
    if (window.$bty) {
        await window.$bty.jsStore.setStore(key, value)
    } else {
        localStorage.setItem(key, value)
    }
}
export const getStore = async (key: string, defaultValue?: any) => {
    let value = null
    if (window.$bty) {
        value = await window.$bty.jsStore.getStore(key, defaultValue)
    } else {
        value = localStorage.getItem(key) || defaultValue
    }
    try {
        value = JSON.parse(value)
    } catch (e) {}
    return value
}
export const delStore = async (key: string) => {
    if (window.$bty) {
        await window.$bty.jsStore.deleteStore(key)
    }
    await localStorage.removeItem(key)
}
export const getPageQuery = () => {
    const { href } = window.location
    const qsIndex = href.indexOf('?')
    const sharpIndex = href.indexOf('#')
    if (qsIndex !== -1) {
        if (qsIndex > sharpIndex) {
            return parse(href.split('?')[1])
        }
        return parse(href.slice(qsIndex + 1, sharpIndex))
    }
    return {}
}
export const sleep = async (time: number) => {
    return new Promise<void>((resolve) => {
        setTimeout(() => resolve(), time)
    })
}
